const { onMsg } = require(`${process.root}/util`);
const engineUrlMap = [
  { label: "baidu", cnName: '百度', value: 'https://www.baidu.com/', prefix: 's?', key: 'wd' },
  { label: "bing", cnName: '必应', value: 'https://cn.bing.com/', prefix: 'search?', key: 'q' },
  { label: "google", cnName: '谷歌', value: 'https://www.google.com/', prefix: 'search?', key: 'q' }
]
const reg = new RegExp(`(?<engine>${engineUrlMap.map(item=>`(${item.label})|(${item.cnName})`).join('|')})\\s+?(?<content>.+)`,'i');

module.exports = {
  name: 'search-engine',
  main: ({ data }) => {
    onMsg(data, async msg => {
      const res = reg.exec(msg);
      if (!res?.groups) return;
      const engine = res.groups.engine;
      const content = res.groups.content;
      if (!engine || !content) return;
      try {
        for (const item of engineUrlMap) {
          if ((item.cnName === engine) || (item.label === engine.toLowerCase())) {
            const message = encodeURI(`${item.value}${item.prefix}${item.key}=${content}`);
            return { message }
          }
        }
        return { message: `search-engine: 暂未添加该搜索引擎` }
      } catch (e) {
        console.log(e);
        return { message: 'search-engine: 参数错误' }
      }
    }, { checkAdmin: false, checkAt: false, checkName: false})
  }
}
